﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml.Linq;

namespace FluentlyXml.Core.Deserialization.BuiltInDeserializers
{
	internal class ListDeserializer : ITypeDeserializer
	{
		public bool CanDeserialize(Type type)
		{
			return type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IList<>);
		}

		public object Deserialize(Type target, XElement element, IDeserializationContext context)
		{
			var itemType = target.GetGenericArguments()[0];
			var listType = typeof (List<>).MakeGenericType(itemType);
			var list = Activator.CreateInstance(listType);
			var addMethod = listType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);

			Action<object> addToList = o => addMethod.Invoke(list, new[] { o });

			foreach (var childElement in element.Elements())
			{
				var childObject = context.Deserialize(itemType, childElement, context);

				addToList(childObject);
			}

			return list;
		}

		public object GetIdentityFor(object obj)
		{
			return obj;
		}
	}
}